function event_onChangeCompanyType()
{
    var company_type = parseInt($("#company_type").val());

    if (company_type == 3)
    {
        $("#pool").val("0");

        $("#tr_select_pool").css("display", "");

        $("#ip").attr("disabled", "disabled").val("");
        $("#vlan").attr("disabled", "disabled").val("");
        $("#vlan_pc").attr("disabled", "disabled").val("");
    }
    else
    {
        if (parseInt($("#previous_type").val()) == 3)
        {
            $("#tr_select_pool").css("display", "none");

            $("#ip").removeAttr("disabled").val("");
            $("#vlan").removeAttr("disabled").val("");
            $("#vlan_pc").removeAttr("disabled").val("");
        };
    };

    $("#previous_type").val(company_type);
};


function event_onChangePool()
{
    var pool_id = parseInt(document.getElementById("pool").value);

    if (pool_id == 0)
    {
        $("#ip").val("");
        $("#vlan").val("");
        $("#vlan_pc").val("");
    }
    else
    {
        var ajax_request = createHTTPPostRequest("/viewbycompany/pool");
        ajax_request.onreadystatechange = function()
        {
            if (ajax_request.readyState == 4)
            {
                if (ajax_request.status == 200)
                {
                    var properties = eval('(' + ajax_request.responseText + ')');

                    $("#ip").val(properties['ip']);
                    $("#vlan").val(properties['vlan_id']);
                    $("#vlan_pc").val(properties['vlan_pc_id']);
                };
            };
        };
        ajax_request.send("id=" + pool_id);
    };
};


function event_onChange_CompanyID(ext_id)
{
    var accounts_list = $('#spa_ext_' + ext_id);
    accounts_list.empty();
    accounts_list.append("<option value=\"-1\" selected>Empty</option>");

    if (parseInt(document.getElementById("company_id_" + ext_id).value) != -1)
    {
        var ajax_request = createHTTPPostRequest("/accounts/getlist");
        ajax_request.onreadystatechange = function()
        {
            if (ajax_request.readyState == 4)
            {
                if (ajax_request.status == 200)
                {
                    var accounts_array = eval('(' + ajax_request.responseText + ')');
                    for (var account in accounts_array)
                        accounts_list.append("<option value=\"" + accounts_array[account]["id"] + "\">Login: " + accounts_array[account]["login"] + " (Display name: " + accounts_array[account]["display_name"] + "; Short name: " + accounts_array[account]["short_name"] +  ")</option>");
                };
            };
        };
        ajax_request.send("company_id=" + document.getElementById("company_id_" + ext_id).value);
    };
};


function event_onChange_Firmware()
{
    var ajax_request = createHTTPRequest();
    ajax_request.open("POST", "/firmwares/version", false);
    ajax_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    ajax_request.send("version=" + encodeURIComponent(document.getElementById("file").files[0].name));
    var version = eval('(' + ajax_request.responseText + ')')['version'];

    var user_version = document.getElementById("version").value;
    document.getElementById("firmware_version").value = version;

    var show_div = true;

    if (version != "")
    {
        if (user_version == "")
            $('#li_version_guess').text('Guessed version [' + version + ']');
        else if (user_version != version)
            $('#li_version_guess').text('Entered version [' + user_version + '] is differ from guessed version [' + version + ']');
        else
            show_div = false;
    }
    else
        $('#li_version_guess').text('Can\'t guess version - bad file?');

    document.getElementById("version_guess").style.display = (show_div ? "" : "none");
};


function event_onKeyPress_FirmwareVersion(evt)
{

    var version = document.getElementById("firmware_version").value;
    var user_version = document.getElementById("version").value;

    if (version != "")
    {
        if (version != user_version)
        {
            document.getElementById("version_guess").style.display = "";
            $('#li_version_guess').text('Entered [' + user_version + '] version is differ from guessed version: [' + version + ']');
        }
        else
            document.getElementById("version_guess").style.display = "none";
    };
};


function event_onClick_Web_Server_Enable()
{
    var web_server_disabled = !$("#web_server_enable").attr("checked");

    document.getElementById("tr_web_server_port").style.display = (web_server_disabled ? "none" : "");
    document.getElementById("tr_web_admin_access_enable").style.display = (web_server_disabled ? "none" : "");
    document.getElementById("tr_web_admin_password").style.display = ((web_server_disabled || (!$("#web_admin_access_enable").attr("checked"))) ? "none" : "");
};


function event_onClick_CheckboxTextarea(checkbox_id, textarea_id, direct_order, clean)
{
    if ($("#" + checkbox_id).attr("checked"))
    {
        document.getElementById(textarea_id).disabled =  ((typeof(direct_order) == "undefined") || (direct_order)) ?  "" : "disabled";
    }
    else
    {
        document.getElementById(textarea_id).disabled =  ((typeof(direct_order) == "undefined") || (direct_order)) ? "disabled" : "";
        if ((typeof(clean) != "undefined") && (clean))
            document.getElementById(textarea_id).value = '';
    };
};



function event_onClick_CheckboxTextarea_Ajax(checkbox_id, textarea_id, ruri, direct_order, clean)
{
    if ($("#" + checkbox_id).attr("checked"))
    {
        // TODO: AJAX LOADER!!!
        runAjax({
            container: checkbox_id,
            ruri: ruri,
            args: "",
            on_status_200: function(responseText) {
                document.getElementById(textarea_id).value = responseText;
            }

        });
        document.getElementById(textarea_id).disabled =  ((typeof(direct_order) == "undefined") || (direct_order)) ?  "" : "disabled";
    }
    else
    {
        document.getElementById(textarea_id).disabled =  ((typeof(direct_order) == "undefined") || (direct_order)) ? "disabled" : "";
        if ((typeof(clean) != "undefined") && (clean))
            document.getElementById(textarea_id).value = '';
    };

};


function setMenuItemsHeight()
{
    var work_area_height = $('#center').innerHeight() - 1;
    var menu_height = $(".menu_item").outerHeight();
    var menu_items_count = 0;

    $(".menu_item").each(function()
    {
        menu_items_count++;
    });

    $(".submenu").css("height", work_area_height - (menu_height * menu_items_count) + "px");
}

function navigateMenu(menu, level, fn)
{
    if ($("#submenu_" + menu).is(":visible"))
    {
        $("#submenu_" + menu).slideUp('');
        fn({action: 'index', use_inner: true, no_apply: true});
    }
    else
    {
        $('.submenu').slideUp('');
        $("#submenu_" + menu).slideDown('');

        expandMenu({id: 0, controller: menu.split("_").join(""), level: level});
    };
};


$(document).ready(function()
{
    setMenuItemsHeight();
    $(window).resize(function(){ setMenuItemsHeight(); });


    $("#right_menu ul li").live("click", function()
    {
        $("#right_menu ul li").removeClass("active");
        $(this).addClass("active");
    });


    $(".submenu ul li a").live("click", function()
    {
        $(".submenu ul li a").removeClass("active");
        $(this).addClass("active");
    });


	$('#search_text').keypress(function(e)
    {
		if(e.which == 13)
        {
			$("#search_results").slideDown();
			if (!($("#search_results_field").is(':visible')))
			{
				$("#search_results").height("100%");
				$("#search_results_field").slideDown();
			}
			doSearch(document.getElementById('search_text').value, document.getElementById('search_area').value, 'search_results_field');
	    }
	});


	$('#search_area').keypress(function(e)
    {
		if(e.which == 13){
			$("#search_results").slideDown();
			if (!($("#search_results_field").is(':visible')))
			{
				$("#search_results").height("100%");
				$("#search_results_field").slideDown();
			}
			doSearch(document.getElementById('search_text').value, document.getElementById('search_area').value, 'search_results_field');
	    }
	});
	

    $('#menu_view_by_company').click(function() { navigateMenu("view_by_company", EXPAND_VIEW_BY_COMPANY, ajaxViewByCompany); });
    $('#menu_accounts').click(function() { navigateMenu("accounts", EXPAND_ACCOUNTS, ajaxAccounts); });
	$('#menu_types').click(function() { navigateMenu("types", EXPAND_TYPES, ajaxTypes); });
	$('#menu_settings').click(function() { navigateMenu("settings", EXPAND_SETTINGS, ajaxSettings); });
    $('#menu_users').click(function() { navigateMenu("users", EXPAND_USERS, ajaxUsers); });


	$("#button_show_menu").click(function() 
	{
		if ($("#hide_part").is(':visible'))
		{
			$("#hide_part").slideUp();
			$("#search_field").slideDown('fast');
		}
		else
		{
			$("#search_field").slideUp('fast');
			$("#hide_part").slideDown();
		}
	});


	$(".search_button").click(function()
	{
		$("#search_results").slideDown();
		if (!($("#search_results_field").is(':visible')))
		{
			$("#search_results_field").slideDown();
			$("#search_results").height("100%");
		}
	});


	$("#search_show_btn").click(function() {
		if ($("#search_results_field").is(':visible'))
		{
			$("#search_results_field").slideUp();
			$("#search_results").height(30);
            $(this).text("Показать результаты поиска");
		}
		else
		{
			$("#search_results").height("100%");
			$("#search_results_field").slideDown();
            $(this).text("Скрыть результаты поиска");
		}
	});

    $("#main_menu li a").click(function()
    {
        if ($(this).attr("href") == "")
        {
            if (!($(this).parent().hasClass("active")))
            {
                $("#main_menu li").removeClass("active");
                $(this).parent().addClass("active");
            }
            return false;
        }
    });
});